package cn.lut.crowd.service.impl;

import cn.lut.crowd.entity.po.Address;
import cn.lut.crowd.entity.po.AddressExample;
import cn.lut.crowd.entity.po.Order;
import cn.lut.crowd.entity.po.OrderProject;
import cn.lut.crowd.entity.vo.OrderProjectVO;
import cn.lut.crowd.entity.vo.OrderVO;
import cn.lut.crowd.mapper.AddressMapper;
import cn.lut.crowd.mapper.OrderMapper;
import cn.lut.crowd.mapper.OrderProjectMapper;
import cn.lut.crowd.service.api.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @user:dell
 * @date:2021年01月23 11:03
 */
@Service
@Transactional(readOnly = true)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderProjectMapper orderProjectPOMapper;

    @Autowired
    private OrderMapper orderPOMapper;

    @Autowired
    private AddressMapper addressPOMapper;


    @Override
    public OrderProjectVO getOrderProjectVO(Integer projectId, Integer returnId) {

        return orderProjectPOMapper.selectOrderProjectVO(returnId);
    }

    @Override
    public List<Address> getAddressVOList(Integer memberId) {

        AddressExample example = new AddressExample();

        example.createCriteria().andMemberIdEqualTo(memberId);

        List<Address> addressPOList = addressPOMapper.selectByExample(example);

        List<Address> addressVOList = new ArrayList<Address>();

        for (Address addressPO : addressPOList) {
            Address addressVO = new Address();
            BeanUtils.copyProperties(addressPO, addressVO);

            addressVOList.add(addressVO);
        }

        return addressVOList;
    }

    @Override
    public void saveAddress(Address addressVO) {
        Address addressPO = new Address();

        BeanUtils.copyProperties(addressVO, addressPO);

        addressPOMapper.insert(addressPO);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void saveOrder(OrderVO orderVO) {

        Order orderPO = new Order();

        BeanUtils.copyProperties(orderVO, orderPO);

        OrderProject orderProjectPO = new OrderProject();

        BeanUtils.copyProperties(orderVO.getOrderProjectVO(), orderProjectPO);

        // 保存orderPO自动生成的主键是orderProjectPO需要用到的外键
        orderPOMapper.insert(orderPO);

        // 从orderPO中获取orderId
        Integer id = orderPO.getId();

        // 将orderId设置到orderProjectPO
        orderProjectPO.setOrderId(id);

        orderProjectPOMapper.insert(orderProjectPO);
    }


}
